import { getToken, setToken, removeAll, setCache, PERMISSIONS_KEY, ROLES_KEY, USER_KEY } from '@/utils/session';
import { login, logout, getUserInfo, getRouters } from '@/api/user';
import { resetRouter } from '@/router';

const state = {
  accountInfo: null,
  token: getToken() || ''
};

const mutations = {
  SET_TOKEN(state, token) {
    state.token = token;
    setToken(token);
  },
  SET_USERINFO(state, userInfo) {
    state.accountInfo = userInfo;
    setCache(USER_KEY, userInfo);
  },
  SET_PERMISSIONS(state, permissions) {
    setCache(PERMISSIONS_KEY, permissions);
  },
  SET_ROLES(state, roles) {
    setCache(ROLES_KEY, roles);
  }
};

const actions = {
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo).then(res => {
        const { data } = res;
        if (data) {
          commit('SET_TOKEN', data.token);
        }
        resolve();
      }).catch(err => {
        reject(err);
      });
    });
  },

  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        commit('SET_TOKEN', '');
        commit('SET_USERINFO', '');
        removeAll();
        resetRouter();
        resolve();
      }).catch(err => {
        reject(err);
      });
    });
  },
  
  getRouters() {
    return new Promise((resolve, reject) => {
      getRouters().then(res => {
        const { data } = res;
        resolve(data);
      }).catch(err => {
        reject(err);
      });
    });
  },

  getUserInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserInfo().then(res => {
        const { data } = res;
        if (data) {
          commit('SET_USERINFO', data.user);
          commit('SET_PERMISSIONS', data.permissions);
          commit('SET_ROLES', data.roles);
        }
        resolve(data.user);
      }).catch(err => {
        reject(err);
      });
    });
  },

  updateInfo({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      commit('SET_USERINFO', userInfo);
      resolve();
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
